/* -----------------------------------------------------------------------
 * Programmer:   Cody Hazelwood
 * Date:         December 5, 2012
 * Platform:     JavaScript / Web
 * Dependencies: WebSocket Support
 * -----------------------------------------------------------------------
 * Description:  
 */

function connect() {
    var status         = $('#status');      //Allows quickly updating the status DIV
    var input          = $('#input');       //IP Address Input
    var button         = $('#button');      //Connect Button
    var msg_info       = $('#msg_info');    //Display for Messages

    var address = 'ws://' + input.val() + ':5001';

    window.WebSocket = window.WebSocket || window.MozWebSocket;

    //Check for WebSocket Support
    if (!window.WebSocket) {
        status.text('No WebSocket Support!');
        return;
    }

    status.text('Attempting Connection: ' + address);

    var connection = new WebSocket(address);

    //Connection is Opened
    connection.onopen = function () {
        status.text('Connection Established!');
        button.attr('value', 'Disconnect');     //Updates connect button to allow disconnect
        button.attr('onclick', 'document.location.reload(true)');
    };

    //Connection Error
    connection.onerror = function (error) {
        status.text('Connection Error!');
    };

    //Message is Recieved
    connection.onmessage = function (message) {
        status.text('Message Recieved');
        
        try {
            var jsonMessage = JSON.parse(message.data).toString();
                msg_info.prepend('<span id="message">' + 
                                      jsonMessage + '<br>' +
                                  '</span>');
        } catch (e) {
            console.log('Corrupt or invalid message received.');
            return;
        }
    };
	
	//Send message at Enter Key Press
	input.keydown(function(e) {
        if (e.keyCode === 13) {
            var msg = $(this).val();
            status.text('Sent Message');
            connection.send(JSON.stringify({ "msg": msg }));
            $(this).val('');
        }
    });

    //Timeout Notification
    setInterval(function() {
        if (connection.readyState !== 1) {
            status.text('Unable to communicate with the WebSocket Server.');
        }
    }, 5000);
}
